package vn.intelsoft.vlogvn.instance;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import vn.intelsoft.vlogvn.R;

import android.os.Environment;

public class Rest {
	public final static String PATH_SDCARD = Environment
			.getExternalStorageDirectory().getPath();

	public static List<Vlogger> getVlogger(String response) {
		List<Vlogger> vloggers = new ArrayList<Vlogger>();

		try {
			JSONArray jsonArray = new JSONArray(response);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject2 = (JSONObject) jsonArray.get(i);

				Vlogger vlogger = new Vlogger(jsonObject2.getString("name"),
						jsonObject2.getString("thumb"),
						jsonObject2.getString("banner"),
						jsonObject2.getString("username"));
				vloggers.add(vlogger);
			}
		} catch (JSONException e) {
			Log.e(e.getMessage());
		}

		return vloggers;
	}

	public static ArrayList<Vlog> getVlogFromJSON(String response) {
		if (response == null || response == "")
			return null;
		ArrayList<Vlog> vlogs = new ArrayList<Vlog>();

		try {
			JSONObject jsonObject = new JSONObject(response);
			JSONObject jsonData = jsonObject.getJSONObject("data");
			JSONArray jsonArray = jsonData.getJSONArray("items");

			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject vlogObject = jsonArray.getJSONObject(i);
				JSONObject thumbnailObject = vlogObject
						.getJSONObject("thumbnail");
				JSONObject contentObject = vlogObject.getJSONObject("content");
				JSONObject playerObject = vlogObject.getJSONObject("player");

				Vlog vlog = new Vlog(vlogObject.getString("id"),
						vlogObject.getString("title"),
						vlogObject.getString("description"),
						thumbnailObject.getString("sqDefault"),
						thumbnailObject.getString("hqDefault"),
						playerObject.getString("default"),
						contentObject.getString("5"), vlogObject
								.getString("uploaded").substring(0, 16)
								.replace("T", " "),
						vlogObject.getInt("viewCount"),
						vlogObject.getInt("likeCount"),
						vlogObject.getInt("duration"));

				vlogs.add(vlog);
			}

		} catch (JSONException e) {
			Log.e(e.getMessage());
		}
		vlogs = sortVlogByDate(vlogs);

		return vlogs;
	}

	private static ArrayList<Vlog> sortVlogByDate(ArrayList<Vlog> vlogs) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			for (int i = 0; i < vlogs.size() - 1; i++) {
				for (int j = i + 1; j < vlogs.size(); j++) {
					Vlog vlog = vlogs.get(i);
					String strDate = vlog.uploadTime;
					Date dateUpload = dateFormat.parse(strDate);

					Vlog vlogCompare = vlogs.get(j);
					String strCompare = vlogCompare.uploadTime;
					Date dateCompare = dateFormat.parse(strCompare);

					if (dateUpload.compareTo(dateCompare) < 0) {
						vlogs.set(i, vlogs.get(j));
						vlogs.set(j, vlog);
					}
				}
			}
		} catch (ParseException e) {
			Log.e(e.getMessage());
		}
		return vlogs;
	}

	public static String getJsonString(String url) {
		String jsonString = null;
		HttpURLConnection linkConnection = null;
		try {
			URL linkurl = new URL(url);
			linkConnection = (HttpURLConnection) linkurl.openConnection();
			int responseCode = linkConnection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream linkinStream = linkConnection.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int j = 0;
				while ((j = linkinStream.read()) != -1) {
					baos.write(j);
				}
				byte[] data = baos.toByteArray();
				jsonString = new String(data);
			}
		} catch (Exception e) {
			Log.e(e.getMessage());
		} finally {
			if (linkConnection != null) {
				linkConnection.disconnect();
			}
		}
		return jsonString;
	}

	public static String getJsonString(JSONObject jsonObject, String sessionId,
			String url) {
		HttpClient client = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(client.getParams(), 30000); // Timeout
																				// Limit
		HttpResponse response;
		String strReturn = "";

		try {
			HttpPost post = new HttpPost(url);
			post.setHeader("Content-Type", "application/json;charset=utf-8");
			// post.addHeader("Cookie", "ASP.NET_SessionId=" + sessionId);

			StringEntity se = new StringEntity(jsonObject.toString());
			// se.setContentEncoding(new BasicHeader("Content-Type",
			// "application/json;charset=utf-8"));
			se.setContentEncoding(new BasicHeader("Content-Type",
					"application/x-www-form-urlencoded"));
			post.setEntity(se);
			response = client.execute(post);
			/* Checking response */
			if (response != null) {
				InputStream in = response.getEntity().getContent(); // Get the
																	// data in
																	// the
																	// entity
				strReturn = convertStreamToString(in);
			}
		} catch (Exception e) {
			Log.e(e.getMessage());
		}
		return strReturn;
	}

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

}
